package sk.naive.talker.command;

import sk.naive.talker.*;
import sk.naive.talker.persistence.*;
import sk.naive.talker.props.PropertyStoreException;
import sk.naive.talker.util.*;
import sk.naive.talker.message.*;

import java.rmi.RemoteException;
import java.util.Date;

/**
 * @author <a href="mailto:rytier@naive.deepblue.sk">Martin "Rytier" Kerni</a>
 * @version $Revision: 1.16 $ $Date: 2005/02/16 19:27:21 $
 */
public class Motd extends AbstractCommand {
	public static final String TPROP_MOTD = "motd";

	public void exec()
		throws CommandException,
		RemoteException, PropertyStoreException
	{
		if (params != null && "edit".startsWith(params.toLowerCase())) {
			Utils.checkPermission(user, Consts.PERM_SUPERUSER);
			new EditorHelper(this).start(getTalker());
			return;
		}
		StringBuilder sb = new StringBuilder();
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + "serverVersion", getTalker().messageFactory().getString("server.version", user.getProperties()));
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + "serverCreated", Utils.createDate(getTalker().getProperties().get(Consts.TPROP_CREATED)));
		ctxSet(DefaultMessageFactory.CTXKEY_VAL + "current", new Date());
		sb.append(getString("motd.head", user.getProperties()));
		sb.append((String) getTalker().get(TPROP_MOTD));
		sb.append(getString("motd.tail", user.getProperties()));
		user.send(sb.toString());
	}

	private class EditorHelper extends AbstractEditorHelper {
		public EditorHelper(AbstractCommand comm) {
			super(Motd.this.user, comm);
		}

		protected Text getOriginalText(final PersistentObject object, TextPersistence db) throws PropertyStoreException {
			return new Text(null) {
				public void setContent(String content, TextPersistence tp) {
					try {
						object.set(Motd.TPROP_MOTD, Utils.unquoteButBr(content));
					} catch (PropertyStoreException e) {
						Utils.unexpectedExceptionWarning(e);
					}
				}

				public String getContent() {
					try {
						String content = (String) object.get(Motd.TPROP_MOTD);
						return Utils.quoteButBr(content);
					} catch (PropertyStoreException e) {
						Utils.unexpectedExceptionWarning(e);
					}
					return null;
				}
			};
			/* TODO, ked bude talker props v DB (konecne ;-)) (pouvazovat aj o spolocnom predkovi pre tuto metodu)
			List<Text> texts = db.loadTexts(object.getId(), textType(), "");
			if (texts.isEmpty()) {
				return null;
			}
			return texts.get(0);
			*/
		}

		protected int textType() {
			return -1;
		}

		protected void sendNotify() throws RemoteException {
			super.sendNotify();
			sendHelper().sendGlobal(user, null, "motd.changed", Category.SYSTEM);
		}

		protected Text createNewText(TextPersistence tp, String s) throws PersistenceException {
			return null; // TODO mozno ked to bude DB
//			return new Text(tp, s);
		}
	}
}
